#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.IO;
using System.Diagnostics;

namespace Osh
{
	/// <summary>
	/// Implements IPacketStream interface over a Stream object.
	/// </summary>
	public class PacketStreamWrapper : PacketStream
	{
		private Stream _stream;
		private int _fixedPacketSize;

		protected PacketStreamWrapper(Stream stream)
		{
			if(stream == null)
				throw new ArgumentNullException("stream");
			_stream = stream;
		}

		public PacketStreamWrapper(Stream stream, int fixedPacketSize) : this(stream)
		{
			if(fixedPacketSize <= 0)
				throw new ArgumentOutOfRangeException("fixedPacketSize");

			_fixedPacketSize = fixedPacketSize;
			this.PacketBuffer = new byte[fixedPacketSize];
		}

		public virtual Stream BaseStream
		{
			get { return _stream; }
		}

		#region PacketStreamBase Overrides
		protected override bool MoveToNextPacketInternal()
		{
			this.PacketSize = _fixedPacketSize;
			this.PacketPosition = 0;

			return Utils.ReadStream(_stream, this.PacketBuffer, 0, this.PacketSize);
		}

		public override void Close()
		{
			_stream.Close();
			base.Close();
		}
		#endregion PacketStreamBase Overrides
	}
}
